#include <iostream>
#include <cstdio>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <string>
#include <cstring>
using namespace std;

const int NUM = 1024;

#define ERROR_EXIT(m)       \
    do                      \
    {                       \
        perror(m);          \
        exit(EXIT_FAILURE); \
    } while (0)

// EXIT_FAILURE  是系统自己定义的宏，用于表示错误返回

void Writer(int wfd)
{
    string s = "hello, I am child";
    pid_t pid = getpid();
    int number = 0;

    char buffer[NUM];
    while (1)
    {
        //  char ch='c';"
        snprintf(buffer, sizeof(buffer), "%s-%d-%d", s.c_str(), pid, number++);
        write(wfd, &buffer, strlen(buffer)); // 这里需不需要 strlen +1  不需要，在文件中没有\0 作为字符串结尾的概念
        sleep(1);
                                //  cout<<number<<endl;
                                // if(number==5) break;
    }
}

void Reader(int rfd)
{
    char buffer[NUM];
    int number=0;
    while (true)
    {
        sleep(1);
        buffer[0] = 0;                                 // 清楚上次缓存
        ssize_t n = read(rfd, buffer, sizeof(buffer)); // 写的话可以用strlen 但是读的话必须得用sizeof了
        if (n > 0)                                     // 判断是否读到数据
        {
            buffer[n] = 0;
            cout << "father get a message {" << getpid() << "]#" << buffer << endl;
        }
        else if(n==0)
        {
            printf("father read end\n");
            break;         
        }
        else break;   
        number++;  
        if(number==5) break;
    }
}

int main()
{
    int pipefd[2];
    if (pipe(pipefd) == -1) // 创建管道
    {
        ERROR_EXIT("pipe error");
    }
    pid_t pid = fork(); // 创建管道之后创建子进程
    if (pid == -1)
        ERROR_EXIT("fork error");
    // 开始关闭多余fd，本次实现为子向父通信，所以关闭子的读，父的写
    if (pid == 0)
    {
        // 子
        close(pipefd[0]);
        Writer(pipefd[1]);
        close(pipefd[1]);
        exit(EXIT_SUCCESS);
    }
    // 父

    close(pipefd[1]);
    Reader(pipefd[0]);
    close(pipefd[0]);  //提前关掉读端
    cout<<"father close read fd "<<pipefd[1]<<endl;
    sleep(5);   //观察僵尸进程
    int status=0;
    pid_t rid=waitpid(pid,&status,0); // 等待子进程结束
    if(rid<0) return 3; //回收失败返回值
    cout<<"wait childe success:"<< rid<<' '<< ((status>>8)&0xff)<<' '<<"exit signal:"<<(status&0x7f)<<endl; // 打印子进程结束状态
    sleep(5);

    // 父进程结束
    cout<<"father end"<<endl;
    
    return 0;
}
